﻿using System;
using System.Collections.Generic;
using System.Linq;
using HQPad.DAL;
using HQPad.Models;

namespace HQPad.Services
{
    public interface IRulesService
    {
        RuleSet GetDefaultRules();
        RuleSet GetRules(int ruleSetId);
        PointsTable GetPointsTable(string className, string race);
        IEnumerable<string> GetRaces(int ruleSetId);
        IEnumerable<string> GetClasses(int ruleSetId);
    }

    public class RulesService : IRulesService
    {
        private HQContext context = null;

        public RulesService(IUnitOfWork context)
        {
            this.context = (HQContext)context;
        }

        public RuleSet GetDefaultRules()
        {
            return context.RuleSets.FirstOrDefault();
        }

        public RuleSet GetRules(int ruleSetId)
        {
            return context.RuleSets.Find(ruleSetId);
        }

        #region GetPointsTable
        /// <summary>
        /// Get a points table by the class and name.
        /// </summary>
        /// <param name="className">The class name like 'Acolyte'.</param>
        /// <param name="race">The race name like 'Elf'</param>
        /// <returns>The table found or null.</returns>
        public PointsTable GetPointsTable(string className, string race)
        {
            return (from p in context.PointsTables
                    where p.Class.ToLower() == className.ToLower().Trim() &&
                    p.Race.ToLower() == race.ToLower().Trim()
                    select p)
                    .FirstOrDefault();
        }
        #endregion

        /// <summary>
        /// Get all distinct race names for a rule set.
        /// </summary>
        /// <param name="ruleSetId"></param>
        /// <returns></returns>
        public IEnumerable<string> GetRaces(int ruleSetId)
        {
            return (from p in context.PointsTables
                    where p.RuleSetID == ruleSetId
                    orderby p.Race
                    select p.Race)
                    .Distinct();
        }

        /// <summary>
        /// Get all distinct class names for a rule set.
        /// </summary>
        /// <param name="ruleSetId"></param>
        /// <returns></returns>
        public IEnumerable<string> GetClasses(int ruleSetId)
        {
            return (from p in context.PointsTables
                    where p.RuleSetID == ruleSetId
                    orderby p.Class
                    select p.Class)
                    .Distinct();
        }
    }
}